package com.osdp.auth.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.osdp.auth.server.ISysOauth2ClientService;
import com.osdp.auth.vo.SysOauth2ClientVo;
import com.osdp.common.http.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oauthClient")
public class Oauth2Controller {

    @Autowired
    private ISysOauth2ClientService sysOauth2ClientService;

    @GetMapping("/list")
    public IPage<SysOauth2ClientVo> pageList(SysOauth2ClientVo oauth2ClientVo,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return sysOauth2ClientService.pageList(oauth2ClientVo,new Page<>(pageNo, pageSize));
    }

    @PostMapping("/save")
    public Result save(@RequestBody Map<String,Object> data) {
        String clientId = MapUtils.getString(data,"clientId");
        if(StringUtils.isEmpty(clientId)){
            return Result.fail("clientId can not be empty or null");
        }

        String secret = MapUtils.getString(data,"secret");
        if(StringUtils.isEmpty(secret)){
            return Result.fail("secret can not be empty or null");
        }

        String grantTypes = MapUtils.getString(data,"grantTypes");
        if(StringUtils.isEmpty(grantTypes)){
            return Result.fail("grantTypes can not be empty or null");
        }

        String redirectUri = MapUtils.getString(data,"redirectUri");
        if(StringUtils.isEmpty(redirectUri)){
            return Result.fail("redirectUri can not be empty or null");
        }
        String tenantId = MapUtils.getString(data,"tenantId");

        boolean ok = sysOauth2ClientService.saveOauth2Client(clientId, secret, grantTypes, redirectUri, tenantId);
        if(ok){
            return Result.success("save client success");
        }
        return Result.fail("save client fail");
    }

    @DeleteMapping("/delete")
    public boolean delete(@RequestBody List<String> ids) {
        return sysOauth2ClientService.deleteOauth2Client(ids);
    }

    @PutMapping("/update")
    @ApiOperation("修改客户端信息")
    public boolean update(@RequestBody SysOauth2ClientVo oauth2ClientVo) {
        return sysOauth2ClientService.updateOauth2Client(oauth2ClientVo);
    }

}
